<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖和节流</title>
</head>
<body>
    <input type="text" class="input1">
    <input type="text" class="input2">
    <input type="text" class="input3">
    <div>一段时间内，多次触发同一个函数，防抖只触发最后一次，节流只触发第一次</div>
    <div>防抖适用于搜索框输入</div>
    <div class="throttle">节流适用于鼠标不断点击、滚动事件监听等</div>

    <script>
        let input1 = document.getElementsByTagName('input')[0];
        let input2 = document.getElementsByClassName('input2')[0];

        function Ajax(content) {
            let date = new Date();
            console.log(date.getMinutes() + ':' + date.getSeconds());
        }

        function debounce(fun, delay) {
            return function(args) {
                let that = this;
                let _args = args;
                clearTimeout(fun.id);
                fun.id = setTimeout(function() {
                    fun.call(that, _args);
                }, delay);
            }
        }

        function throttle(fun, delay) {
            let lastTime, timer;
            return function(args) {
                let that = this;
                let _args = arguments;
                let now = +new Date();
                
                if(lastTime && now < lastTime + delay) {
                    clearTimeout(timer);
                    timer = setTimeout(() => {
                        lastTime = now;
                        fun.apply(that, _args);
                    }, delay);
                }
                else
                {
                    lastTime = now;
                    fun.apply(that, _args);
                }
            }
        }

        let debounceAjax = debounce(Ajax, 1000);

        input1.addEventListener('keyup', function(e) {
            debounceAjax(e.target.value);
        });

        let throttleAjax = throttle(Ajax, 3000);

        let div = document.getElementsByClassName('throttle')[0];
        div.addEventListener('click', function(e) {
            throttleAjax('click');
        })

        let timer = 0;
        input2.addEventListener('input', function(e) {
            clearTimeout(timer);
            let str = e.target.value;
            timer = setTimeout(function() {
                let date = new Date();

                console.log(date.getTime());
            }, 1000);
        });

        // 防抖: 每次重复触发就重新计时，一定时间后再去触发


    </script>
</body>
</html>